<script setup>
import {computed, reactive, ref, watch} from 'vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: '新增',
  },
  data: {
    type: Object,
    default: () => ({
      id: "",
      name: "",
      code: "",
      status: "",
      content: "",
    })
  }
})

const rules = reactive({
  'name': [
    {required: true, message: '名称不能为空', trigger: 'blur'},
  ],
  'code': [
    {required: true, message: '编码不能为空', trigger: 'blur'},
  ],
  'content': [
    {required: true, message: '描述不能为空', trigger: 'blur'},
  ],
  'status': [
    {required: true, message: '请选择状态', trigger: 'change'},
  ]
})

const isVisible = computed(() => props.visible)

const role =  ref({...props.data})
watch(() => props.data, (val) => {
  role.value = {...val}
})

const formRef = ref(null)

//定义子父通信事件
const emit = defineEmits(['update:visible', "confirm"])

//状态枚举类
const statusEnum = ref([
  {label: "启用", value: 1 },
  {label: "禁用", value: 2 },
])

//关闭Dialog
const closeDialog = () => {
  emit('update:visible', false)
}

//确认Dialog
const confirmDialog = () => {
  if (!formRef.value) return
  formRef.value.validate((valid) => {
    if (valid) {
      emit('confirm', role.value)
    }
  })
}

//监听关闭回调
const handleClose = () => {
  closeDialog()

  formRef.value.clearValidate()
  formRef.value.resetFields()
}
</script>

<template>
<el-dialog v-model="isVisible" title="添加" width="360px" @close="handleClose" :close-on-click-modal="false">
  <el-form :model="role" ref="formRef" rules="rules">
    <el-form-item label="名称" prop="name">
      <el-input v-model="role.name" placeholder="请输入角色名" maxlength="32" />
    </el-form-item>
    <el-form-item label="编码" prop="name">
      <el-input v-model="role.code" placeholder="请输入角色编码" maxlength="16" />
    </el-form-item>
    <el-form-item label="状态" prop="status">
      <el-select placeholder="请选择状态" v-model="role.status">
        <el-option v-for="(item, index) in statusEnum" :key="index" :label="item.label" :value="item.value" />
      </el-select>
    </el-form-item>
    <el-form-item label="简介" prop="content">
      <el-input type="textarea" maxlength="500" rows="6" v-model="role.content" show-word-limit />
    </el-form-item>
  </el-form>
  <template #footer>
    <el-button @click="closeDialog">取消</el-button>
    <el-button type="primary" @click="confirmDialog">确认</el-button>
  </template>
</el-dialog>
</template>

<style scoped lang="scss">

</style>
